package org.zjkoye.crm.controller;

import io.micrometer.common.lang.Nullable;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zjkoye.crm.common.PageResultBean;
import org.zjkoye.crm.common.Result;
import org.zjkoye.crm.entity.Usermain;
import org.zjkoye.crm.service.RegionService;
import org.zjkoye.crm.service.UsermainService;
import org.zjkoye.crm.utils.JwtUtil;
import org.zjkoye.crm.utils.Sha256Utils;
import org.zjkoye.crm.utils.ThreadLocalUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zjkoye
 * @since 2024-06-23
 */
@Tag(name = "用户接口MAIN")
@RestController
@RequestMapping("/usermain")
public class UsermainController
{
    private static final Logger logger = LoggerFactory.getLogger(UserController.class); //日志输出类

    @Autowired
    private UsermainService usermainService;

    @Autowired
    private RegionService regionService;

    @Operation(summary = "用户注册")
    @Parameters({
            @Parameter(name = "username", description = "用户名", required = true, schema = @Schema(type = "string")),
            @Parameter(name = "password", description = "密码", required = true, schema = @Schema(type = "string")),
            @Parameter(name = "fullName", description = "全名", required = true, schema = @Schema(type = "string")),
            @Parameter(name = "phone", description = "电话号码", schema = @Schema(type = "string")),
            @Parameter(name = "email", description = "邮箱", required = true, schema = @Schema(type = "string"))
    })
    @PostMapping("/register")
    public CompletableFuture<Result<Void>> registerUser(@RequestBody Usermain userDto) {
        CompletableFuture<Boolean> usernameExistsFuture = usermainService.existsByUsername(userDto.getUsername());
        CompletableFuture<Boolean> emailExistsFuture = usermainService.existsByEmail(userDto.getEmail());

        return usernameExistsFuture.thenCombine(emailExistsFuture, (usernameExists, emailExists) -> {
            if (usernameExists) {
                return Result.error("用户名已存在");
            } else if (emailExists) {
                return Result.error("邮箱已被注册");
            } else {
                boolean hasDigit = false;
                boolean hasLetter = false;
                boolean hasSpecialChar = false;
                String password = userDto.getPassword();

                for (int i = 0; i < password.length(); i++) {
                    char ch = password.charAt(i);
                    if (Character.isDigit(ch)) {
                        hasDigit = true;
                    } else if (Character.isLetter(ch)) {
                        hasLetter = true;
                    } else {
                        hasSpecialChar = true;
                    }
                }
                if (!hasDigit || !hasLetter || !hasSpecialChar) {
                    return Result.error("密码错误密码最小长度8个字符，需要包括字母、数字和特殊符号3种");
                }

                if(!regionService.isExist(userDto.getRegionName()))
                    return Result.error("当前地区未添加到地区表中请联系管理员");

                userDto.setPassword(Sha256Utils.sha256(userDto.getPassword()));
                userDto.setRole(userDto.getRole().equals("admin") ? "管理员" : "业务员");
                userDto.setStatus("活跃"); // 默认设置为活跃状态
                userDto.setdeleted(0);
                return usermainService.add(userDto).join();
            }
        }).thenApply(result -> {
            if (result.isSuccess()) {
                return Result.success();
            } else {
                return Result.error(result.getMessage());
            }
        });
    }

    @Operation(summary = "用户登录")
    @Parameters({
            @Parameter(name = "username", description = "登录名", required = true, schema = @Schema(type = "string")),
            @Parameter(name = "password", description = "密码", required = true, schema = @Schema(type = "string"))
    })
    @PostMapping("/login")
    public CompletableFuture<Result<String>> loginUser(@RequestBody Usermain user) {
        logger.debug("开始认证");

        if (user == null || "".equals(user.getUsername()) || "".equals(user.getPassword())) {
            return CompletableFuture.completedFuture(Result.error("用户名密码不能为空"));
        }
        logger.info(user.toString());
        return usermainService.findByUsername(user.getUsername()).thenApply(eruser -> {
            if (eruser == null) {
                return Result.error("用户名不存在");
            }

            if (Sha256Utils.sha256(user.getPassword()).equals(eruser.getPassword())) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", eruser.getUserId());
                claims.put("name", eruser.getUsername());
                //claims.put("loginName", eruser.getPassword());
                claims.put("regionName",eruser.getRegionName());
                ThreadLocalUtil.set(eruser);
                String token = JwtUtil.getToken(claims);

                logger.info(eruser.toString());
                return Result.success(token);
            }

            logger.debug("认证失败");
            return Result.error("密码错误");
        });
    }

    @GetMapping("/pageList")
    @Operation(summary = "用户列表分页查询")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "pageSize", required = true, description = "每页显示的条数"),
            @Parameter(name = "currentPage", required = true, description = "要查询的页"),
            @Parameter(name = "name", description = "用户姓名", required = false)
    })
    public CompletableFuture<Result<PageResultBean<Usermain>>> pageList(@RequestParam int pageSize, @RequestParam int currentPage, @Nullable @RequestParam String name) {
        return usermainService.pageList(pageSize, currentPage, name).thenApply(page -> {
            if (page == null) {
                return Result.error("查询失败");
            }
            PageResultBean<Usermain> pageResultBean = new PageResultBean<>(page.getTotal(), page.getRecords());
            return Result.success(pageResultBean);
        });
    }

    @GetMapping("/pagerecovery")
    public CompletableFuture<Result<PageResultBean<Usermain>>> pagerecovery(@RequestParam int pageSize, @RequestParam int currentPage) {
        return usermainService.pagerecovery(pageSize,currentPage).thenApply( page-> {
                if(page == null) {
                    return Result.error("查询失败");
                }
                PageResultBean<Usermain> pageResultBean = new PageResultBean<>(page.getTotal(), page.getRecords());
                return Result.success(pageResultBean);
            }
        );
    }
    @GetMapping("/restore/{id}")
    public Result<String> restore(@PathVariable int id) {
        usermainService.recovery(id);
        return Result.success("恢复成功");
    }
    @GetMapping("/deleteforever/{id}")
    public Result<String> deleteforever(@PathVariable int id) {
        usermainService.deleteforever(id);
        return Result.success("该员工已经永久删除");
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除用户信息")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "id", required = true, description = "用户id")
    })
    public CompletableFuture<Result<String>> delete(@PathVariable int id) {
        return usermainService.deleteById(id).thenApply(result -> {
            if (!result) {
                return Result.error("删除失败");
            }
            return Result.success("删除成功");
        });
    }



    @GetMapping("/currentUser")
    @Operation(summary = "获取当前登录用户信息")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public CompletableFuture<Result<Usermain>> getCurrentUser() {
        Map<String, Object> userSession = ThreadLocalUtil.get();
        int id = (int) userSession.get("id");

        return usermainService.getUserById(id).thenApply(user -> {
            if (user != null) {
                return Result.success(user);
            }
            return Result.error("用户状态异常");
        });
    }

    @PostMapping("/add")
    @Operation(summary = "添加用户")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public CompletableFuture<Result<String>> addUser(@RequestBody Usermain userDto) {
        Usermain user = ThreadLocalUtil.get();
        if(userDto.getRegionName().isEmpty() || userDto.getRegionName() == null)
            userDto.setRegionName(user.getRegionName());
        return usermainService.add(userDto).thenApply(result -> {

            if(!regionService.isExist(userDto.getRegionName()))
                return Result.error("当前地区未添加到地区表中请联系管理员");

            if(result.isSuccess())
                return Result.success("添加成功");
            else
                return Result.error(result.getMessage());
        });
    };

    @GetMapping("/getuserById")
    @Operation(summary = "根据id查询用户信息")
    @Parameters({
            @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token"),
            @Parameter(name = "id", required = true, description = "用户id")
    })
    public CompletableFuture<Result<Usermain>> getUserById(@RequestParam int id) {
        return usermainService.getUserById(id).thenApply(user -> {
            if (user == null) {
                return Result.error("获取用户信息失败");
            }
            return Result.success(user);
        });
    }

    @PutMapping("/update")
    @Operation(summary = "修改用户信息")
    @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, description = "token")
    public CompletableFuture<Result<String>> update(@RequestBody Usermain user) {
        return usermainService.updateUser(user).thenApply(result -> {
            if (!result) {
                return Result.error("修改失败");
            }
            if(!regionService.isExist(user.getRegionName()))
                return Result.error("当前地区未添加到地区表中请联系管理员");
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getUserId());
            claims.put("name", user.getUsername());
            //claims.put("loginName", eruser.getPassword());
            claims.put("regionName",user.getRegionName());
            ThreadLocalUtil.set(user);
            //String token = JwtUtil.getToken(claims);
            logger.info("!!!!!!!!!!!!!!!!!!!!!!!" + ThreadLocalUtil.get());
            return Result.success("修改成功");
        });
    }


    @GetMapping("/permission")
    public CompletableFuture<Result<Boolean>> permission() {
        Map<String, Object> userSession = ThreadLocalUtil.get();
        int id = (int) userSession.get("id");

        return usermainService.getUserById(id).thenCompose(user -> usermainService.permission(user.getUserId()).thenApply(Result::success));
    }


}
